import logging
from django.shortcuts import render
from django.views import View
from django import http
from collections import OrderedDict

from goods.models import ContentCategory
from meiduo_mall.utils.response_code import RETCODE
from content.utils import get_categories
# Create your views here.

logger = logging.getLogger('django')


class IndexView(View):
    """首页视图"""
    def get(self, request):
        """
        商品分类
        {
            "1":{
                "channels":[
                    {"id":1, "name":"手机", "url":"http://shouji.jd.com/"},
                    {"id":2, "name":"相机", "url":"http://www.itcast.cn/"}
                ],
                "sub_cats":[
                    {
                        "id":38,
                        "name":"手机通讯",
                        "sub_cats":[
                            {"id":115, "name":"手机"},
                            {"id":116, "name":"游戏手机"}
                        ]
                    },
                    {
                        "id":39,
                        "name":"手机配件",
                        "sub_cats":[
                            {"id":119, "name":"手机壳"},
                            {"id":120, "name":"贴膜"}
                        ]
                    }
                ]
            },
            "2":{
                "channels":[],
                "sub_cats":[]
            }
        }
        """
        # 查询商品信息
        categories_dict = get_categories()

        # 查询广告信息
        """
        {
            'content_category1': [
                {
                    'text': '',
                    'title': '',
                    'url': '',
                    'image': ''
                },
                {
                    'text': '',
                    'title': '',
                    'url': '',
                    'image': ''
                }
            ],
            'content_category2': {}
        }
        """
        # 创建广告字典
        contents_dict = OrderedDict()
        # 获取广告种类对象列表
        contents_category_list = ContentCategory.objects.all()
        # 遍历广告种类列表
        for contents_category in contents_category_list:
            # 取出该对象的所有要展示的广告
            # 构建数据
            contents_dict[contents_category.key] = [
                {
                    'title': content.title,
                    'url': content.url,
                    'image': content.image,
                    'text': content.text
                }
                for content in contents_category.content_set.filter(status=True).order_by('sequence')
            ]

        context = {
            'categories': categories_dict,
            'contents': contents_dict
        }

        return render(request, 'index.html', context=context)
